<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Post extends Front_Controller {
	public function __construct()
    {
        parent::__construct();
		$this->load->model('post_model');
		$this->load->library(array('pagination','security'));
		$this->load->model(array('user_model','captcha_model','comment_model'));
		$this->load->helper(array('breabcrumb','security'));
    }

	public function index($addr, $category_id=0, $sub_cat_id=0, $child_cat_id=0 ,$page_number = 1){
		$data = array();
		//lay danh sach tin va phan trang
        $page = $this->uri->segment(3);
        if(empty($page)){
            $page=1;
        }
        if($category_id==6){
            $page_size = 50;
        }else {
            $page_size = 20;
        }
        $page_url   = get_post_find_url($this->province_id, $category_id, $sub_cat_id, $child_cat_id);
        $total_rows = $this->post_model->count_all($this->province_id, $category_id, $sub_cat_id, $child_cat_id);
        $records = $this->post_model->find_list_posts($this->province_id, $category_id, $sub_cat_id, $child_cat_id, $page_size, $page);
        $pagination = $this->get_paging($page_url, $total_rows, $page, $page_size );
        $data = array(
            "total" => $total_rows,
            "records" => $records,
            "pagination" => $pagination
        );
		$data['tags']="";
		$data['title']="Trang chu";
		$data['category_id']=$category_id;
		$data['sub_cat_id']=$sub_cat_id;
		$data['child_cat_id']=$child_cat_id;
		$this->layout->view($data);
	}

	function detail($post_id){

		$data = array();
		$item = $this->post_model->getSingle($post_id);
		$before_province_id = get_cookie ( COOKIE_PROVINCE_ID );
		if ($before_province_id != $item['provinder_id'] || empty($before_province_id)) {
			set_cookie( COOKIE_PROVINCE_ID, $item['provinder_id'],0);
		}
		$data['user_post']		= 	$this->user_model->getSingle($item['user_id']);
        //update so luot view
        $this->post_model->update_hit($post_id,$item['hit']);
		$params =array();
        $data['comment']= $this->comment_model->get_list_comment_post($post_id);
        $data['category_id']    =   $item['cat_id'];
        $data['sub_cat_id']     =   $item['sub_cat_id'];
        $data['child_cat_id']     =   $item['child_cat_id'];
		$data['item'] 			= 	$item;
		$data['title']			=	"Trang chu";
        $data['append_js']  =   $this->layout->js(array('assets/js/jQuery/jquery.tinyscrollbar.min.js'));
        $data['source_js']=$this->layout->source_js("$('#scrollbar1').tinyscrollbar();");
		$this->layout->view($data);
	}


	function edit($id=null){
		$this->load->library('form_validation');
		$data = array();
        $getUser = getUser();
        $this->config->load('uploading_script');
		$this->form_validation->set_rules('name', 'Tiêu đề', 'required|min_length[20]');
		$this->form_validation->set_rules('category', 'Chuyên mục', 'required');
		$this->form_validation->set_rules('provinder', 'Nơi rao', 'required');
        //$this->form_validation->set_rules('captcha', 'Mã an toàn', 'required|callback_captcha_check');
        $this->form_validation->set_rules('content', 'Nội dung tin', 'required|min_length[100]');
		if ($this->form_validation->run() == TRUE){
			$obj =array();
			$obj['name'] 			= converString($this->input->post('name'));
			$obj['mobile'] 			= $this->input->post('phone');
            $category               = $this->category_model->getSingle($this->input->post('category'));
            $obj['cat_id']          = $category['parent'];
            $obj['sub_cat_id']      = $this->input->post('category');
            $childen                = $this->input->post('childen');
			$obj['child_cat_id'] 	= isset($childen)?$childen:0;
			$obj['provinder_id'] 	= $this->input->post('provinder');
			$obj['content'] 		= tagsString($this->input->post('content'));
			$obj['price']			= $this->input->post('price');
			$obj['promotion']			= $this->input->post('promotion');
			$obj['image']			= $this->input->post('image');
            $post_id = $this->input->post('post_id');
			if($post_id>0){
				$obj['modifyTime']		= time();
				$this->post_model->update($obj,$post_id);
				redirect(get_post_detail_url($post_id,$obj['name']));
			}else {
				$obj['status']			= 1;
				$obj['user_id'] 		= $getUser['id'];
                $obj['modifyTime']		= time();
				$obj['createdTime']		= time();
				$insert_id = $this->post_model->save($obj);
				redirect(get_post_detail_url($insert_id,$obj['name']));
			}
		}
        $post=array();
        if($id){
            $post=$this->post_model->getSingle($id);
        }
        $data['post']=$post;
        $this->load->model('captcha_model');
        $data['captcha'] = $this->captcha_model->make_captcha();
        $data['append_js']  =   $this->layout->js(array('assets/js/tooltip/form-field-tooltip.js',
            'assets/js/tooltip/rounded-corners.js','assets/js/ajaxupload.js'));
        $data['append_css'] =   $this->layout->css(array('assets/js/tooltip/form-field-tooltip.css'));
        $data['category_id']=0;
		$this->layout->view($data);
	}
    function deleteimage(){
        $imgurl = $this->input->post('imgurl');
        $imgurl = base_url(substr($imgurl,1));
        @unlink($imgurl);
        echo json_encode(array('status'=>true));
        exit();
    }

    public function comment(){
        $obj =array();
        $obj['phone'] = $this->input->post('phone');
        $obj['email'] = $this->input->post('email');
        $obj['comment'] = $this->input->post('comment');
        $obj['user_id'] = $this->input->post('user_id');
        $obj['post_id'] = $this->input->post('post_id');
        if(empty($obj['user_id'])){
            $obj['user_id']=0;
            $avatar =  'medias/images/noavatarx44x44.jpg';
        }else {
            $user_post = $this->user_model->getSingle($obj['user_id']);
            $avatar= $user_post['avatar'];
        }
        $obj['parent'] = $this->input->post('parent');
        $obj['status'] = 1;
        $obj['createdTime']=time();
        $this->db->insert('comments', $obj);
        $data=array();
        $html="";
        if($this->db->insert_id()){
            $this->memcached->delete('all_comment_post_'.$obj['post_id']);
            $data['status']=1;
            if($obj['parent']!=0){
                $html.='<div class="subItem">
                            <div class="subAvatar"><img src="'.$avatar.'" onerror="this.src=\'medias/images/noavatarx44x44.jpg\'"></div>
                            <div class="subInfo">
                            <div class="clear">';
                                if(!empty($obj['user_id'])){
                                    $html.='<a href="#"><span><strong>'.getByUser($obj['user_id'],2).'</strong></span></a>';
                                }else {
                                    $html.= "<span><strong>".$obj['phone']."</strong></span>";
                                }

                                $html.=':&nbsp;<span>'.$obj['comment'].'</span>';
                            $html.='</div>
                            <div class="clear" style="padding-top: 2px;">
                                <span class="date_reply">'.getRemainingTime($obj['createdTime']).'</span>

                            </div>
                        </div>
                    </div>';

            }else {

                $html.='
                    <div class="itemComment">
                        <div class="u-avatar"><img src="'.$avatar.'" onerror="this.src=\'medias/images/noavatarx44x44.jpg\'"></div>
                        <div class="cmInfo">
                            <div class="mList">
                                <div class="clear">';
                                    if(!empty($obj['user_id'])){
                                        $html.='<a href="#"><span><strong>'.getByUser($obj['user_id'],2).'</strong></span></a>';
                                    }else {
                                        $html.="<span><strong>".$obj['phone']."</strong></span>";
                                    }

                                    $html.=':&nbsp;<span>'.$obj['comment'].'</span>
                                </div>
                                <div class="clear" style="padding-top: 2px;">
                                    <span class="date_reply">'.getRemainingTime($obj['createdTime']).'</span>
                                    <span class="reply" datafld="'.$this->db->insert_id().'">Trả lời</span>
                                </div>
                            </div>
                            <div class="subAllForm" id="itemComment'.$this->db->insert_id().'"></div>
                        </div>
                    </div>
                ';
            }
            $data['msg']=$html;
        }else {
            $data['status']=-1;
            $data['msg']="Có lỗi xảy ra xin vui lòng làm lại.";
        }
        echo json_encode($data);
        exit();
    }
}
